﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace Telepathy.Protocols
{
    public class MessageBase
    {
        public MessageBase(HeaderType headerType)
        {
            this.headerType = headerType;
            bytes = new byte[0];
        }

        HeaderType _headerType = HeaderType.Content;
        public HeaderType headerType
        {
            get { return _headerType; }
            protected set
            {
                int maxValue = 256 * 256;
                if ((int)value > maxValue)
                {
                    Debug.LogError(string.Format(" 数值大于byte数组头部2位了! 头部数值不能大于:{0}", maxValue));
                    _headerType = (HeaderType)maxValue;
                }
                _headerType = value;
            }
        }

        /// <summary>
        /// 本次发送消息的ID 用户名+序号
        /// </summary>
        public string messageId;
        /// <summary>
        /// 字符串数据内容
        /// </summary>
        public string text;
        /// <summary>
        /// byte数组数据内容
        /// </summary>
        public byte[] bytes;

        /// <summary>
        /// 获取全部数据长度
        /// </summary>
        public int allBytesLength
        {
            get
            {
                return ExcBytesLength + bytes.Length;
            }
        }
        /// <summary>
        /// 获取除了byte数组部分长度的所有数据长度
        /// </summary>
        public int ExcBytesLength
        {
            get
            {
                int len = Encoding.UTF8.GetBytes(messageId.ToString()).Length +
                    Encoding.UTF8.GetBytes(text).Length;
                return len;
            }
        }

        /// <summary>
        /// 序列化消息
        /// </summary>
        /// <param name="writer"></param>
        public byte[] Serialize()
        {
            MessageSerialize txtClass = new MessageSerialize();
            txtClass.id = messageId;
            txtClass.text = text;
            string strData = JsonConvert.SerializeObject(txtClass);
            byte[] Datas = GetBytes(headerType, strData, bytes);
            return Datas;
        }
        /// <summary>
        /// 全部头部长度7位 前2位头部信息 中2位文本长度, 在后3位bytes内容长度 byte[]{信息2位,文本长度2位,bytes长度3位, 文本bytes, bytes}
        /// </summary>
        /// <param name="headervalue"></param>
        /// <param name="text"></param>
        /// <param name="data"></param>
        protected static byte[] GetBytes(HeaderType hType, string text, byte[] data)
        {
            List<byte> _header = new List<byte>();
            //添加头部
            int hValue = (int)hType;
            _header.Add((byte)(hValue / 256));
            _header.Add((byte)hValue);
            //添加内容头部
            byte[] txt = Encoding.UTF8.GetBytes(text);
            _header.Add((byte)(txt.Length / 256));
            _header.Add((byte)txt.Length);
            //添加bytes内容头部
            _header.Add((byte)(data.Length / (256 * 256)));
            _header.Add((byte)(data.Length / 256));
            _header.Add((byte)(data.Length));
            //添加文本内容byte数组
            _header.AddRange(txt);
            _header.AddRange(data);
            return _header.ToArray();
        }

        /// <summary>
        /// 解析消息
        /// </summary>
        /// <param name="reader"></param>
        public static MessageBase Deserialize(byte[] datas)
        {
            int statrIndex = 7;//固定头部长度
            //读取头部
            int headerBuffer = datas[0] * 256 + datas[1];
            int txtLength = datas[2] * 256 + datas[3];
            int bytesLength = datas[4] * 256 * 256 + datas[5] * 256 + datas[6];
            byte[] textBuffer = new byte[txtLength];
            byte[] bytesBuffer = new byte[bytesLength];
            //MyDebug.LogError(string.Format("datas:{0}", string.Join(",", datas)));
            //MyDebug.LogError(string.Format("头部:{0} 文本:{1} bytes:{2}", headerBuffer, txtLength, bytesLength));
            Array.Copy(datas, statrIndex, textBuffer, 0, txtLength);
            statrIndex = txtLength + statrIndex;
            if (bytesLength > 0) Array.Copy(datas, statrIndex, bytesBuffer, 0, bytesLength);
            string textString = Encoding.UTF8.GetString(textBuffer);
            MessageSerialize txtClass = JsonConvert.DeserializeObject<MessageSerialize>(textString);
            //MyDebug.LogWarning(string.Format("bytes:{0} 字符:{1}  -  {2}  -  {3}", string.Join(",", textBuffer), textString, txtClass.id, txtClass.text));
            MessageBase msg = new MessageBase((HeaderType)headerBuffer);
            msg.messageId = txtClass.id;
            msg.text = txtClass.text;
            msg.bytes = bytesBuffer;
            return msg;
        }

    }

}